<?php
namespace Modules\Groupon\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Order\Entities\UnionOrder;
use Modules\Order\Entities\ProductOrder as Order;
use Modules\Product\Entities\Sku;

use Modules\Groupon\Entities\GrouponSku;

use Validator;
use ThrowException;
use Auth;

class PreviewGrouponOrderController extends Controller
{
    public function store(Request $req)
    {
        $rule = [
            'skus' => ['required', 'array'],
            'skus.*.id' => ['required'],
            'skus.*.total' => ['required'],
            // 'address_id' => ['integer'],
            // 'coupon_id' => ['integer']
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $isNeedAddress = 0;
        $orders = [];
        $address = null;

        $grouponSku = GrouponSku::getEntity([
            'id' => $req->input('skus')[0]['id'],
            'with' => ['groupon', 'base_sku']
        ]);

        $sku = $grouponSku->base_sku ?: ThrowException::Conflict('sku不存在');
        $total = $req->input('skus')[0]['total'];
        $sku->isCanBuy($user, $total);
        
        $skuableMaps = [
            [
                'skuable' => $grouponSku,
                'total' => $total
            ]
        ];

        // 准备收货地址(如果有)
        $address = $user->getAddressOrDefault($req->input('address_id'));

        // 准备优惠券
        $userCoupon = $user->coupons()->valid()->where('id', $req->input('coupon_id'))->first();

        // // 创建统一订单
        // $unionOrder = new UnionOrder();
        $order = Order::initWith($skuableMaps, $user, $address, [
            'coupon' => $userCoupon
        ]);

        $skus = [];
        foreach ($order->skusTemp as $orderSku) {
            $info = $orderSku->getInfo([
                'sku_id',
                'sku_uuid',
                'thumb',
                'title',
                'attrs',
                'original_price',
                'selling_price',
                'total',
            ]);
            array_push($skus, $info);
        }

            // 计算可用优惠券
        $coupons = $order->filterCoupons($user->coupons()->with('base_coupon')->valid()->get());

        $orderInfo = [
            'skus' => $skus,
            'coupons' => $coupons,
            'carriage' => $order->carriage,
            'coupon_discount' => $order->coupon_discount,
            'product_price' => $order->product_price,
            'price' => $order->pay_price
        ];

        return [
            'is_need_address' => $isNeedAddress,
            'address' => $address,
            'order' => $orderInfo
        ];
    }
}
